#!/usr/bin/env python3
"""
学术研究自动化系统状态检查脚本
"""

import os
import sys
import sqlite3
import json
from pathlib import Path
from datetime import datetime

def check_python_version():
    """检查Python版本"""
    print("🐍 Python版本检查:")
    version = sys.version_info
    print(f"   当前版本: {version.major}.{version.minor}.{version.micro}")
    
    if version >= (3, 8):
        print("   ✅ Python版本符合要求 (>= 3.8)")
        return True
    else:
        print("   ❌ Python版本过低，需要3.8或更高版本")
        return False

def check_dependencies():
    """检查依赖包"""
    print("\n📦 依赖包检查:")
    
    required_packages = {
        'flask': 'Flask',
        'flask_cors': 'Flask-CORS', 
        'requests': 'requests',
        'sqlite3': 'sqlite3 (内置)',
        'json': 'json (内置)',
        'uuid': 'uuid (内置)',
        'datetime': 'datetime (内置)',
        'pathlib': 'pathlib (内置)'
    }
    
    missing = []
    
    for module, name in required_packages.items():
        try:
            __import__(module)
            print(f"   ✅ {name}")
        except ImportError:
            print(f"   ❌ {name}")
            missing.append(name)
    
    if missing:
        print(f"\n⚠️  缺少依赖: {', '.join(missing)}")
        return False
    
    print("   ✅ 所有核心依赖已安装")
    return True

def check_directories():
    """检查目录结构"""
    print("\n📁 目录结构检查:")
    
    required_dirs = [
        'data',
        'data/uploads',
        'data/cache', 
        'data/exports',
        'templates',
        'static',
        'agents',
        'tools',
        'utils'
    ]
    
    missing_dirs = []
    
    for directory in required_dirs:
        if Path(directory).exists():
            print(f"   ✅ {directory}")
        else:
            print(f"   ❌ {directory}")
            missing_dirs.append(directory)
    
    if missing_dirs:
        print(f"\n⚠️  缺少目录: {', '.join(missing_dirs)}")
        print("   💡 运行系统时会自动创建")
    
    return len(missing_dirs) == 0

def check_database():
    """检查数据库"""
    print("\n🗄️  数据库检查:")
    
    db_path = 'data/research.db'
    
    if not Path(db_path).exists():
        print("   ❌ 数据库文件不存在")
        print("   💡 首次运行时会自动创建")
        return False
    
    try:
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        # 检查主要表
        tables = ['projects', 'research_plans', 'literature', 'experiment_designs']
        
        for table in tables:
            cursor.execute(f"SELECT name FROM sqlite_master WHERE type='table' AND name='{table}'")
            if cursor.fetchone():
                print(f"   ✅ 表 {table}")
            else:
                print(f"   ❌ 表 {table}")
        
        # 检查数据统计
        cursor.execute("SELECT COUNT(*) FROM projects")
        project_count = cursor.fetchone()[0]
        print(f"   📊 项目数量: {project_count}")
        
        cursor.execute("SELECT COUNT(*) FROM literature")
        literature_count = cursor.fetchone()[0]
        print(f"   📚 文献数量: {literature_count}")
        
        conn.close()
        print("   ✅ 数据库连接正常")
        return True
        
    except Exception as e:
        print(f"   ❌ 数据库错误: {e}")
        return False

def check_files():
    """检查关键文件"""
    print("\n📄 关键文件检查:")
    
    required_files = [
        'app.py',
        'start.py', 
        'run_system.py',
        'requirements.txt',
        'templates/index.html',
        'templates/projects.html',
        'templates/project_detail.html',
        'implement_real_literature_search.py'
    ]
    
    missing_files = []
    
    for file_path in required_files:
        if Path(file_path).exists():
            size = Path(file_path).stat().st_size
            print(f"   ✅ {file_path} ({size} bytes)")
        else:
            print(f"   ❌ {file_path}")
            missing_files.append(file_path)
    
    if missing_files:
        print(f"\n⚠️  缺少文件: {', '.join(missing_files)}")
        return False
    
    return True

def check_network():
    """检查网络连接"""
    print("\n🌐 网络连接检查:")
    
    try:
        import requests
        
        # 测试arXiv API
        response = requests.get('http://export.arxiv.org/api/query?search_query=all:test&max_results=1', timeout=5)
        if response.status_code == 200:
            print("   ✅ arXiv API连接正常")
        else:
            print("   ⚠️  arXiv API连接异常")
        
    except Exception as e:
        print(f"   ❌ 网络连接测试失败: {e}")
        return False
    
    return True

def generate_report():
    """生成系统状态报告"""
    print("\n" + "="*50)
    print("📋 系统状态报告")
    print("="*50)
    
    checks = [
        ("Python版本", check_python_version()),
        ("依赖包", check_dependencies()),
        ("目录结构", check_directories()),
        ("数据库", check_database()),
        ("关键文件", check_files()),
        ("网络连接", check_network())
    ]
    
    passed = sum(1 for _, result in checks if result)
    total = len(checks)
    
    print(f"\n📊 检查结果: {passed}/{total} 项通过")
    
    if passed == total:
        print("🎉 系统状态良好，可以正常运行！")
        print("\n🚀 启动命令:")
        print("   Windows: start.bat 或 python run_system.py")
        print("   Linux/macOS: ./start.sh 或 python3 run_system.py")
    else:
        print("⚠️  系统存在问题，建议修复后再运行")
        print("\n💡 解决建议:")
        
        for name, result in checks:
            if not result:
                if name == "Python版本":
                    print("   - 升级Python到3.8或更高版本")
                elif name == "依赖包":
                    print("   - 运行: pip install -r requirements.txt")
                elif name == "目录结构":
                    print("   - 运行系统时会自动创建缺少的目录")
                elif name == "数据库":
                    print("   - 首次运行时会自动初始化数据库")
                elif name == "关键文件":
                    print("   - 检查项目文件是否完整")
                elif name == "网络连接":
                    print("   - 检查网络连接和防火墙设置")
    
    print(f"\n📅 检查时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

def main():
    """主函数"""
    print("🔍 学术研究自动化系统状态检查")
    print("="*50)
    
    generate_report()

if __name__ == "__main__":
    main()